<?php

namespace App\Web\Model;

use App\Web\Facades\UserAuth;
use App\Web\Model\Login as LoginModel;
use App\Web\Model\User as UserModel;
use EchoPHP\Facades\Db;
use EchoPHP\Validator\Validator;

/**
 * Class Role
 * 角色管理相关业务逻辑
 * @package App\Web\Model
 */
class Team extends Model {
    private $teamCodeLen = 5; //每级团队code长度
    private $teamMagnitude = 4; //团队级数
    private $connector = ' | ';    //团队名称连接符

    private $fullNameDelimit = '*&*'; //团队全称分隔符

    /**
     * 获取下属团队列表
     * @param $teamCode
     * @param bool $withChildTeam
     * @param null $field
     * @return array
     */
    public function getSubTeamList($teamCode, $withChildTeam = false, $field = null) {
        $field = $field ?? 'teamid,teamcode,teamname,isdefault,fullname';
        $sql = 'SELECT ' . $field . ' FROM Team where status = ? ';
        $var = ['01'];

        if ($withChildTeam) {
            $sql .= ' AND teamcode LIKE ?';
            $var[] = $teamCode . '%';
        } else {
            $sql .= ' AND teamcode LIKE ?';
            $var[] = $teamCode . str_repeat('_', strlen($this->teamCodeLen));
        }

        $sql .= ' ORDER BY teamcode ASC';
        return Db::select($sql, $var);
    }

    /**
     * 获取下属团队列表，如果传入teamcode为空则查询全部团队列表
     * @param $teamCode 当前所在团队
     * @param null $field 查询字段名称
     * @return array
     */
    public function getWorkTeamList($teamCode, $field = null) {
        $field = $field ?? 'teamid,teamcode,teamname,isdefault';
        $sql = 'SELECT ' . $field . ' FROM Team where status = ? ';
        $var = ['01'];

        if (!is_null($teamCode)) {
            $sql .= ' AND teamcode LIKE ?';
            $var[] = $teamCode . '%';
        }

        $sql .= ' ORDER BY teamcode ASC';
        $result = Db::select($sql, $var);

        $teamList = [];
        //处理团队信息
        foreach ($result as $team) {
            $team['teamlevel'] = strlen($team['teamcode']) / $this->teamCodeLen;
            $team['last'] = (strlen($team['teamcode']) / $this->teamCodeLen) >= $this->teamMagnitude;
            $team['show'] = false;
            $currTeam = $this->getTeamStruct($team['teamcode'], $team);
            $teamList = array_merge_recursive($teamList, $currTeam);
        }
        return $teamList;
    }

    /**
     * 获取团队列表
     * teamList中参数定义
     * teamlevel：团队的等级，teamcode长度除以每级团队code的长度
     * last:是否是最后一级团队
     * show:是否展开该团队，默认false
     */
    public function getTeamList() {
        $result = $this->searchAllTeamList('teamid,teamcode,teamname,isdefault', false, true);

        $teamList = [];
        //处理团队信息
        foreach ($result as $team) {
            $team['teamlevel'] = strlen($team['teamcode']) / $this->teamCodeLen;
            $team['last'] = (strlen($team['teamcode']) / $this->teamCodeLen) >= $this->teamMagnitude;
            $team['show'] = false;
            $currTeam = $this->getTeamStruct($team['teamcode'], $team);
            $teamList = array_merge_recursive($teamList, $currTeam);
        }
        if ($isSuper = UserAuth::getLoginInfo('issuper', 0) == 1) {
            $loginTeamCode = '';
        } else {
            $loginTeamCode = UserAuth::getLoginInfo('teamcode', '');
        }

        $teamUserCount = $this->getTeamUserCount();
        return ['status' => true, 'message' => '获取成功', 'teamList' => $teamList, 'teamUserCount' => $teamUserCount];
    }

    /**
     * 将当前团队解析成父级团队的子团队 000010000200003 变为 ['00001'=>['child'=>['0000100002'=>['child'=>['000010000200003'=>['teamid'=>'1','teamname'=>'三级团队']]]]]]
     * @param $teamCode
     * @param $teamInfo
     * @return array
     */
    private function getTeamStruct($teamCode, $teamInfo) {
        $parentCode = substr($teamCode, 0, -$this->teamCodeLen);
        $teamInfo = [$teamCode => $teamInfo];
        if (strlen($parentCode) > 0) {
            return $this->getTeamStruct($parentCode, ['child' => $teamInfo]);
        }
        return $teamInfo;
    }

    /**
     * Notes:获取团队列表，用于添加协作人弹窗下拉项选择团队
     * @param $isSelection
     * @param $defaultTeam
     * @return array
     */
    public function getCleanList($isSelection, $defaultTeam) {
        $result = $this->searchAllTeamList('teamcode,teamname,teamid', $isSelection, $defaultTeam);
        $teamNameList = [];
        $teamCodeList = [];
        foreach ($result as $item) {
            $teamNameList[$item['teamcode']] = $item;

            $teamCodeList[] = $item['teamcode'];
        }

        $teamList = [];
        foreach ($teamCodeList as $teamCode) {
            //获取到当前是第几级别
            $teamLevel = strlen($teamCode) / $this->teamCodeLen;
            $teamItem = &$teamList;
            //整理父级团队信息
            for ($i = 1; $i <= $teamLevel; $i++) {
                $itemTeamCode = substr($teamCode, 0, $i * $this->teamCodeLen);

                if (!isset($teamItem[$itemTeamCode])) {
                    $teamItem[$itemTeamCode] = [
                        'value' => $itemTeamCode,
                        'teamid' => $teamNameList[$itemTeamCode]['teamid'] ?? 0,
                        'label' => $teamNameList[$itemTeamCode]['teamname'] ?? '团队名错误',
                        'children' => []
                    ];
                }
                $teamItem = &$teamItem[$itemTeamCode]['children'];
            }
        }
        $teamList = $this->resetTeamListForClean($teamList);

        return ['status' => true, 'message' => '获取成功', 'teamList' => $teamList];
    }

    /**
     * 重置团队列表
     * @param $itemList
     * @return mixed
     */
    private function resetTeamListForClean($itemList) {
        $newTeamList = [];
        foreach ($itemList as $item) {
            if (!isset($item['children']) || empty($item['children'])) {
                unset($item['children']);
                $newTeamList[] = $item;
            } else {
                $newTeamList[] = array_merge($item, ['children' => $this->resetTeamListForClean($item['children'])]);
            }
        }

        return $newTeamList;
    }

    /**
     * Notes:查询完整团队列表
     * @param null $field
     * @param bool $isSelection
     * @param bool $defaultTeam
     * @return array
     */
    protected function searchAllTeamList($field = null, $isSelection = false, $defaultTeam = false) {
        // 超管可以查看所有团队，普通管理员只能查看当前所在一级团队下数据
        $loginTeamCode = UserAuth::getLoginInfo('teamcode', '');
        $isSuper = UserAuth::getLoginInfo('issuper', 0);
        $parentTeamCode = ($isSuper || $isSelection) ? null : substr($loginTeamCode, 0, 5);

        $field = $field ?? 'teamid,teamcode,teamname,isdefault';
        $sql = 'SELECT ' . $field . ' FROM Team where status = ? ';
        $var = ['01'];

        if (!is_null($parentTeamCode)) {
            $sql .= ' AND teamcode LIKE ?';
            $var[] = $parentTeamCode . '%';
        }
        if ($defaultTeam) {
            $sql .= ' or teamid = ?';
            $var[] = '1';
        }

        $sql .= ' ORDER BY teamcode ASC';
        return Db::select($sql, $var);
    }

    /**
     * 获取团队下用户列表
     * @param string $teamCode
     * @return array
     */
    public function getTeamUserCount($teamCode = '') {
        $sql = 'select teamcode,count(1) as count from User WHERE status=? AND islock=?';
        $var = ['01', 0];

        if (!empty($teamCode)) {
            $sql .= ' AND teamcode LIKE ?';
            $var[] = $teamCode . '%';
        }
        $sql .= ' GROUP BY teamcode';

        $userList = Db::select($sql, $var);

        $startTeamPoint = strlen($teamCode) / $this->teamCodeLen;
        $startTeamPoint = $startTeamPoint > 0 ? $startTeamPoint : 1;

        $teamUserCount = [];
        foreach ($userList as $item) {
            $itemTeamCode = $item['teamcode'];
            for ($i = $startTeamPoint; $i <= strlen($itemTeamCode) / $this->teamCodeLen; $i++) {
                $tmpCode = substr($itemTeamCode, 0, $i * $this->teamCodeLen);
                $teamUserCount[$tmpCode] = isset($teamUserCount[$tmpCode]) ? ($teamUserCount[$tmpCode] + intval($item['count'])) : intval($item['count']);
            }
        }

        return $teamUserCount;
    }

    /**
     * 根据用户角色分析团队下用户成员构成
     * @param $teamCode
     * @return array
     */
    public function analysisTeamUserByRole($teamCode) {
        if (empty($teamCode)) {
            return ['status' => false, 'message' => '参数错误'];
        }
        $loginTeamCode = substr(UserAuth::getLoginInfo('teamcode', ''), 0, $this->teamCodeLen);
        $baseTeamCode = substr($teamCode, 0, $this->teamCodeLen);
        $isSuper = UserAuth::getLoginInfo('issuper', 0);
        if ($baseTeamCode != '00000') {
            if ($isSuper != 1 && $baseTeamCode != $loginTeamCode) {
                return ['status' => false, 'message' => '参数错误'];
            }
        }

        $sql = 'SELECT a.roleid,b.rolename,a.count FROM (SELECT roleid,count(1) as count FROM User WHERE teamcode like ? AND status=? AND islock=? AND roleid>0 GROUP BY roleid) a LEFT JOIN Role b ON a.roleid=b.roleid ORDER BY a.roleid';
        $var = [$teamCode . '%', '01', 0];

        $result = Db::select($sql, $var);
        return ['status' => true, 'message' => '获取成功', 'userCount' => $result,];
    }

    /**
     * 拼接上父级团队名称，例如 000010000200003 => 00001名称 - 0000100002名称 - 000010000200003名称
     * @param $teamInfo
     * @param $teamCode
     * @return string
     */
    private function getTeamName($teamInfo, $teamCode) {
        if (strlen($teamCode) <= $this->teamCodeLen) {
            return $teamInfo[$teamCode]['teamname'];
        }
        $parentCode = substr($teamCode, 0, -$this->teamCodeLen);
        return $this->getTeamName($teamInfo, $parentCode) . $this->connector . $teamInfo[$teamCode]['teamname'];
    }

    /**
     * 新增团队
     * @param $parentCode   父级团队code
     * @param $teamName 团队名称
     * @return array ['status' => true/false, 'message' => '']
     */
    public function addTeam($parentCode, $teamName) {
        $teamName = str_replace('*&*', '***', $teamName);
        $rule = [
            'teamname|团队名称' => [
                'required', 'maxLength' => '50'
            ]
        ];

        $validate = new Validator($rule);
        $result = $validate->validate([
            'teamname' => $teamName,
        ]);
        if (!$result) {
            return ['status' => false, 'message' => '添加失败', 'errorFields' => $validate->getErrors()];
        }

        if (!empty($parentCode)) { //有父级团队
            //超过4级团队暂不支持
            if (strlen($parentCode) >= $this->teamCodeLen * $this->teamMagnitude) {
                return ['status' => false, 'message' => '添加失败', 'errorFields' => ['parentcode' => '只能设置' . $this->teamMagnitude . '级团队']];
            }

            $parentTeamInfo = $this->getTeamInfoByCode($parentCode, 'teamid,teamcode,fullname');
            if (empty($parentTeamInfo)) {
                return ['status' => false, 'message' => '添加失败', 'errorFields' => ['parentcode' => '父级团队不存在']];
            }
            $parentFullName = $parentTeamInfo['fullname'];
        } else {    //没有父级团队把参数置空，防止0,false这些值造成团队code错误
            if (UserAuth::getLoginInfo('issuper') != 1) {
                return ['status' => false, 'message' => '添加失败', 'errorFields' => ['parentcode' => '您不是超级管理员，无新增一级团队权限']];
            }
            $parentCode = '';
            $parentFullName = '';
        }

        //查找同级团队是否有重名的
        $sameName = $this->checkTeamName($parentCode, $teamName);
        if ($sameName) {
            return ['status' => false, 'message' => '添加失败', 'errorFields' => ['teamname' => '已存在同名团队']];
        }

        //查找新团队最大的兄弟团队code，以确认新团队的code
        $teamCode = $this->generateTeamCode($parentCode);

        //插入数据，返回数据库操作结果
        if (empty($parentCode)) {
            //添加一级团队
            $fullName = $this->fullNameDelimit . $teamName . $this->fullNameDelimit;
        } else {
            //添加子团队
            $fullName = $parentFullName . $teamName . $this->fullNameDelimit;
        }

        $sql = 'INSERT INTO Team(teamcode,teamname,createdate,updatedate,status,fullname) values (?,?,now(),now(),?,?)';
        $var = [$teamCode, $teamName, '01', $fullName];
        $result = Db::insert($sql, $var);
        if ($result) {
            $teamInfo = $this->getTeamInfoByCode($teamCode, 'teamid,teamcode,isdefault,teamname');
            if (!empty($teamInfo)) {
                //设置用于前台展示的当前团队级别、是否最后一层团队（4层架构） 是否有子级团队
                $teamInfo['teamlevel'] = strlen($teamInfo['teamcode']) / $this->teamCodeLen;
                $teamInfo['last'] = (strlen($teamInfo['teamcode']) / $this->teamCodeLen) >= $this->teamMagnitude;
                $teamInfo['show'] = false;
            }
            return ['status' => true, 'message' => '添加成功', 'teaminfo' => $teamInfo];
        } else {
            return ['status' => false, 'message' => '添加失败'];
        }

    }

    /**
     * 重命名团队
     * @param $teamCode
     * @param $teamName
     * @return array
     */
    public function editTeam($teamCode, $teamName) {
        //参数校验
        $rule = [
            'teamname|团队名称' => [
                'required', 'maxLength' => '50'
            ],
            'teamcode|团队代码' => [
                'required', 'number'
            ]
        ];
        $msg = [
            'teamcode' => '该团队不存在'
        ];

        $validate = new Validator($rule, $msg);
        $result = $validate->validate([
            'teamname' => $teamName,
            'teamcode' => $teamCode
        ]);
        if (!$result) {
            $errMessages = $validate->getErrors();
            return ['status' => false, 'message' => '修改失败', 'errorFields' => $errMessages];
        }

        //检查兄弟节点是否有重名
        $sameName = $this->checkTeamName(substr($teamCode, 0, 0 - $this->teamCodeLen), $teamName, $teamCode);
        if ($sameName) {
            return ['status' => false, 'message' => '修改失败', 'errorFields' => ['teamname' => '已存在同名团队']];
        }

        //修改数据，返回数据库操作结果
        $sql = 'UPDATE Team SET teamname=?,updatedate=now() WHERE teamcode = ? AND status = ? AND isdefault=?';
        $var = [$teamName, $teamCode, '01', 0];
        $statement1 = Db::prepareStatement($sql, $var);

        $teamLevel = floor(strlen($teamCode) / $this->teamCodeLen);

        $fullNameSql = 'UPDATE Team SET fullname=CONCAT_WS(?,SUBSTRING_INDEX(fullname,?,?),?,SUBSTR(fullname, CHAR_LENGTH(SUBSTRING_INDEX(fullname,?,?)) + ?)) WHERE teamcode LIKE ? AND status = ?';
        $fullNameVar = [$this->fullNameDelimit, $this->fullNameDelimit, $teamLevel, $teamName, $this->fullNameDelimit, $teamLevel + 1, strlen($this->fullNameDelimit) + 1, $teamCode . '%', '01'];
        $statement2 = Db::prepareStatement($fullNameSql, $fullNameVar);

        $result = Db::connect()->prepareTransactionStatement(true, $statement1, $statement2)->execute();

        if ($result) {
            return ['status' => true, 'message' => '修改成功'];
        } else {
            return ['status' => false, 'message' => '修改失败'];
        }
    }

    /**
     * Notes:删除团队，团队status设为'06',同时将User表中属于该团队的人移出团队
     * @param $teamCode
     * @return array
     */
    public function deleteTeam($teamCode) {
        //参数校验
        if (strlen($teamCode) == 0) {
            return ['status' => false, 'message' => '请选择团队',];
        }
        //先查找出团队下所有成员
        $userModel = new UserModel();
        $teamUsers = $userModel->search('userid', [], 0, 0, '', $teamCode);

        //1、删除团队，子团队一起删除
        $sql = 'UPDATE Team SET status=?,updatedate=now() WHERE teamcode LIKE ? AND status = ? AND isdefault=?';
        $var = ['06', $teamCode . '%', '01', 0];
        $statement1 = Db::connect()->prepareStatement($sql, $var);
        //2、团队成员全部移出团队
        $sql = 'UPDATE User SET teamcode=?,teamid=?,teamrole=?,updatedate=now() WHERE teamcode LIKE ?';
        $var = ['00000', 1, 1, $teamCode . '%'];
        $statement2 = Db::connect()->prepareStatement($sql, $var);
        try {
            Db::connect()->prepareTransactionStatement(false, $statement1, $statement2)->execute();
        } catch (\Exception $e) {
            return ['status' => false, 'message' => '删除失败'];
        }
        //下线被移出团队的团队成员
        $loginModel = new LoginModel();
        if (!empty($teamUsers)) {
            foreach ($teamUsers as $user) {
                $loginModel->excluded(0, $user['userid'], '您的账号已被修改，请重新登录');
            }
        }
        return ['status' => true, 'message' => '删除成功'];
    }

    /**
     *  兄弟团队是否有同名的
     * @param $parentTeamCode
     * @param $teamName   团队名称
     * @param null $teamCode
     * @return bool       false - 有重名的 true-无重名的
     */
    private function checkTeamName($parentTeamCode, $teamName, $teamCode = null) {
        //查找同级团队是否有重名的
        $selSql = 'SELECT count(1) as count FROM Team where teamcode like ? AND teamname = ? AND status = ? ';
        $selVar = [$parentTeamCode . str_repeat('_', $this->teamCodeLen), $teamName, '01'];

        if (!empty($teamCode)) {
            $selSql .= ' AND teamcode != ?';
            $selVar[] = $teamCode;
        }

        $result = Db::selectOne($selSql, $selVar);
        return $result['count'] > 0;
    }

    /**
     * 查询团队信息
     * @param $field
     * @param array $search
     * @param int $rowFrom
     * @param int $rowTo
     * @return array
     */
    public function searchTeam($field, $search = [], $rowFrom = 0, $rowTo = 0, $orderBy = '') {
        $sql = 'SELECT ' . $field . ' FROM Team ';
        $var = [];
        $where = [];

        //查询团队
        if (!empty($search['teamcode'])) {
            $where[] = 'teamcode = ?';
            $var[] = $search['teamcode'];
        }

        if (isset($search['teamid'])) {
            $where[] = 'teamid = ?';
            $var[] = $search['teamid'];
        }

        //查询在职状态
        if (isset($search['status']) && in_array($search['status'], ['01', '06'])) {
            $where[] = 'status = ?';
            $var[] = $search['status'];
        }

        if (!empty($where)) {
            $sql .= ' WHERE ' . implode(' AND ', $where);
        }
        //拼接排序
        if (!empty($orderBy)) {
            $sql .= 'ORDER BY ' . $orderBy;
        }

        return Db::select($sql, $var, $rowFrom, $rowTo);
    }

    /**
     * 根据teamcode获取团队信息
     * @param $teamCode
     * @param null $field
     * @return array|mixed
     */
    public function getTeamInfoByCode($teamCode, $field = null) {
        return $this->getTeamInfoByField('teamcode', $teamCode, $field);
    }

    /**
     * 根据团队id获取团队信息
     * @param $teamId
     * @param $field
     * @return array|mixed
     */
    public function getTeamInfoById($teamId, $field) {
        return $this->getTeamInfoByField('teamid', $teamId, $field);
    }

    /**
     * 根据字段名获取团队信息
     * @param $fieldName
     * @param $fieldValue
     * @param null $field
     * @return array|mixed
     */
    private function getTeamInfoByField($fieldName, $fieldValue, $field = null) {
        $field = empty($field) ? 'teamid,teamcode,teamname' : $field;
        $sql = 'SELECT ' . $field . ' FROM Team WHERE ' . $fieldName . '=? AND status=?';
        $var = [$fieldValue, '01'];

        $teamInfo = Db::selectOne($sql, $var);
        return empty($teamInfo) ? [] : $teamInfo;
    }

    /**
     * 生成teamcode
     * @param $parentTeamCode
     * @return string
     */
    public function generateTeamCode($parentTeamCode) {
        $sql = 'SELECT teamcode FROM Team where teamcode like ? ORDER BY teamcode DESC';
        $var = [$parentTeamCode . str_repeat('_', $this->teamCodeLen)];
        $result = DB::selectOne($sql, $var);
        if (empty($result)) {
            $teamIndex = 1;
        } else {
            $teamIndex = intval(substr($result['teamcode'], 0 - $this->teamCodeLen)) + 1;
        }

        return $parentTeamCode . str_pad(strval($teamIndex), $this->teamCodeLen, '0', STR_PAD_LEFT);
    }

    /**团队下一级成员与字团队
     * @param string $teamCode
     * @return array
     */
    public function detail($teamCode = '') {
        $user = UserAuth::getLoginInfo();
        if ($user['teamrole'] == 1) {
            return [];
        }
        if (!$teamCode) {
            $teamCode = $user['teamcode'];
        }
        $sql = 'select teamcode,teamid,teamname,length(teamcode) as codelength from Team where teamcode = ?  and status = ?';
        $teamInfo = Db::selectOne($sql, [$teamCode, '01']);
        $sql = 'select teamcode,teamid,teamname,length(teamcode) as codelength from Team where teamcode like ? and status = ?';
        $childTeam = Db::select($sql, [$teamCode . '%', '01']);
        $sql = 'select userid,username,teamcode,cname from User where teamcode like ?';
        $teamMember = Db::select($sql, [$teamCode . '%']);
        $userMap = [];
        foreach ($teamMember as $key => $item) {
            $teamMember[$key]['value'] = $item['userid'];
            $teamMember[$key]['label'] = $item['cname'];
        }
        foreach ($teamMember as $item) {
            $userMap[$item['teamcode']][] = $item;
        }
        $result = $this->teamTree($childTeam, $teamCode, $teamInfo['codelength'], $userMap);
        $result = array_merge($userMap[$teamCode], $result);
        $teamInfo['children'] = $result;
        $teamInfo['value'] = $teamInfo['teamcode'];
        $teamInfo['label'] = $teamInfo['teamname'];
        return [$teamInfo];
    }

    /**
     * Notes:递归查询子团队以及成员
     * @param $teamList
     * @param $teamCode
     * @param $codeLength
     * @param $userMap
     * @return array
     */
    private function teamTree($teamList, $teamCode, $codeLength, $userMap) {
        $result = [];
        foreach ($teamList as $key => $team) {
            $team['children'] = [];
            $team['value'] = $team['teamcode'];
            $team['label'] = $team['teamname'];
            if (substr($team['teamcode'], 0, $codeLength) == $teamCode && $team['codelength'] == ($codeLength + 5)) {
                $tmpLength = $codeLength + 5;
                $tmpTeam = $this->teamTree($teamList, $team['teamcode'], $tmpLength, $userMap);
                $team['children'] = array_merge($userMap[$team['teamcode']] ?? [], $tmpTeam);
                $result[] = $team;
            }
            unset($teamList[$key]);
        }
        return $result;
    }

    /**
     * Notes: 获取例如 华东-周忠亮-武汉-尹业明 这样完整的团队名
     * @param $teamCode
     * @param string $separator
     * @return string
     */
    public function fullName($teamCode, $separator = '\\') {
        $fullTeamName = [];
        $sql = 'select teamcode,teamname from Team where teamcode like ? and status = ? order by teamcode';
        $teamList = Db::select($sql, [substr($teamCode, 0, 5) . '%', '01']);
        $teamNameMap = [];
        foreach ($teamList as $item) {
            $teamNameMap [$item['teamcode']] = $item['teamname'];
        }
        for ($length = 5; $length <= strlen($teamCode); $length = $length + 5) {
            $fullTeamName [] = $teamNameMap[substr($teamCode, 0, $length)];
        }
        return implode($separator, $fullTeamName);
    }

    /**
     * 获取子级团队树状结构
     * @param $teamCode
     * @return array
     */
    public function getFollowTeamList($teamCode) {
        $result = $this->getSubTeamList($teamCode, true);

        $teamList = [];
        if (!empty($teamCode)) {
            foreach ($result as $key => $item) {
                if ($teamCode == $item['teamcode']) {
                    $itemInfo = $item;
                    $itemInfo['value'] = $itemInfo['teamcode'];
                    $itemInfo['label'] = $itemInfo['teamname'];
                    unset($result[$key]);
                    $itemChild = $this->mergeChildTeamListToTree($item['teamcode'], $result);
                    if (!empty($itemChild)) {
                        $itemInfo['children'] = $itemChild;
                    }
                    $teamList[] = $itemInfo;
                    break;
                }
            }
        } else {
            $teamList = $this->mergeChildTeamListToTree('', $result);
        }
        return $teamList;
    }

    /**
     * 合并子孙团队列表为竖状结构
     * @param $rootTeamCode
     * @param $teamList
     * @return array
     */
    private function mergeChildTeamListToTree($rootTeamCode, $teamList) {
        $childTeamLength = strlen($rootTeamCode) + $this->teamCodeLen;
        $childTeamList = [];
        foreach ($teamList as $key => $item) {
            if (strlen($item['teamcode']) == $childTeamLength && substr($item['teamcode'], 0, strlen($rootTeamCode)) == $rootTeamCode) {
                $itemInfo = $item;
                $itemInfo['value'] = $itemInfo['teamcode'];
                $itemInfo['label'] = $itemInfo['teamname'];
                unset($teamList[$key]);
                $itemChild = $this->mergeChildTeamListToTree($item['teamcode'], $teamList);
                if (!empty($itemChild)) {
                    $itemInfo['children'] = $itemChild;
                }
                $childTeamList[] = $itemInfo;
            }
        }

        return $childTeamList;
    }
}